<template>
  <div class="space-detail-container">
    <a-spin :spinning="loading">
      <div v-if="spaceDetail" class="space-detail">
        <!-- 顶部信息 -->
        <div class="detail-header" :class="getSpaceLevelClass(spaceDetail.spaceLevel)">
          <div class="header-content">
            <div class="header-title">
              <a-tag :color="getSpaceLevelColor(spaceDetail.spaceLevel)">
                {{ getSpaceLevelText(spaceDetail.spaceLevel) }}
              </a-tag>
            </div>
            <div class="header-right">
              <div class="meta-info">
                <span class="meta-item">
                  <UserOutlined />
                  创建者：{{ spaceDetail.createUserName || '未知' }}
                </span>
                <span class="meta-item">
                  <CalendarOutlined />
                  创建于：{{ formatDate(spaceDetail.createTime) }}
                </span>
                <span class="meta-item">
                  <SyncOutlined />
                  更新于：{{ formatDate(spaceDetail.updateTime) }}
                </span>
              </div>
            </div>
          </div>
        </div>

        <!-- 统计卡片 -->
        <div class="stats-section">
          <a-row :gutter="[16, 16]">
            <!-- 存储空间使用 -->
            <a-col :span="8">
              <a-card class="stat-card storage" :class="[getSpaceLevelClass(spaceDetail.spaceLevel)]">
                <template #title>
                  <div class="card-title">
                    <HddOutlined />
                    <span>存储空间</span>
                  </div>
                </template>
                <div class="stat-content">
                  <div class="chart-container">
                    <VChart class="chart" :option="storageChartOption" autoresize />
                  </div>
                  <div class="stat-main">
                    <div class="stat-number">{{ formatSize(spaceDetail.totalSize) }}</div>
                    <div class="stat-label">已使用 / {{ formatSize(spaceDetail.maxSize) }}</div>
                  </div>
                </div>
              </a-card>
            </a-col>

            <!-- 成员统计 -->
            <a-col :span="8">
              <a-card class="stat-card members" :class="[getSpaceLevelClass(spaceDetail.spaceLevel)]">
                <template #title>
                  <div class="card-title">
                    <TeamOutlined />
                    <span>成员统计</span>
                  </div>
                </template>
                <div class="stat-content">
                  <div class="chart-container">
                    <VChart class="chart" :option="memberChartOption" autoresize />
                  </div>
                  <div class="stat-main">
                    <div class="stat-number">{{ spaceDetail.totalMembers }}</div>
                    <div class="stat-label">总成员数</div>
                  </div>
                </div>
              </a-card>
            </a-col>

            <!-- 活跃度 -->
            <a-col :span="8">
              <a-card class="stat-card activity" :class="[getSpaceLevelClass(spaceDetail.spaceLevel)]">
                <template #title>
                  <div class="card-title">
                    <ThunderboltOutlined />
                    <span>空间活跃度</span>
                  </div>
                </template>
                <div class="stat-content">
                  <div class="chart-container">
                    <VChart class="chart" :option="activityChartOption" autoresize />
                  </div>
                </div>
              </a-card>
            </a-col>
          </a-row>
        </div>

        <!-- 成员列表 -->
        <div class="members-section">
          <a-card :class="getSpaceLevelClass(spaceDetail.spaceLevel)" title="成员列表">
            <a-table :dataSource="spaceDetail.members" :columns="memberColumns" :pagination="false">
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'avatar'">
                  <a-avatar :src="IMAGE_PREFIX + record.avatar" />
                </template>
                <template v-else-if="column.key === 'roleName'">
                  <a-tag :color="record.roleName === 'SPACE_ADMIN' ? 'gold' : 'blue'">
                    {{ record.roleName === 'SPACE_ADMIN' ? '管理员' : '成员' }}
                  </a-tag>
                </template>
                <template v-else-if="column.key === 'joinTime'">
                  {{ formatDate(record.joinTime) }}
                </template>
              </template>
            </a-table>
          </a-card>
        </div>
      </div>
    </a-spin>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, computed } from 'vue'
  import { use } from 'echarts/core'
  import { CanvasRenderer } from 'echarts/renderers'
  import { PieChart, LineChart } from 'echarts/charts'
  import { GridComponent, TooltipComponent, LegendComponent } from 'echarts/components'
  import VChart from 'vue-echarts'
  import { useRoute } from 'vue-router'
  import { message } from 'ant-design-vue'
  import {
    UserOutlined,
    TeamOutlined,
    HddOutlined,
    CalendarOutlined,
    SyncOutlined,
    ThunderboltOutlined,
  } from '@ant-design/icons-vue'
  import dayjs from 'dayjs'
  import * as tuanduikongjianmokuai from '@/api/tuanduikongjianmokuai'
  import { IMAGE_PREFIX } from '@/config/constants'

  // 页面状态
  const loading = ref(false)
  const spaceDetail = ref<any>(null)

  // 表格列定义
  const memberColumns = [
    {
      title: '头像',
      key: 'avatar',
      width: 80,
    },
    {
      title: '昵称',
      dataIndex: 'nickName',
      key: 'nickName',
    },
    {
      title: '角色',
      key: 'roleName',
    },
    {
      title: '加入时间',
      key: 'joinTime',
    },
  ]

  // 注册必须的组件
  use([CanvasRenderer, PieChart, LineChart, GridComponent, TooltipComponent, LegendComponent])

  // 获取空间等级文本
  const getSpaceLevelText = (level: number) => {
    const levels: Record<number, string> = {
      0: '普通版',
      1: '专业版',
      2: '旗舰版',
    }
    return levels[level] || '普通版'
  }

  // 获取空间等级颜色
  const getSpaceLevelColor = (level: number) => {
    const colors: Record<number, string> = {
      0: '#52c41a',
      1: '#1890ff',
      2: '#722ed1',
    }
    return colors[level] || '#52c41a'
  }

  // 获取空间等级样式类
  const getSpaceLevelClass = (level: number) => {
    const classes: Record<number, string> = {
      0: 'normal-space',
      1: 'pro-space',
      2: 'flagship-space',
    }
    return classes[level] || 'normal-space'
  }

  // 获取进度条颜色
  const getProgressColors = (level: number) => {
    const colors: Record<number, { '0%': string; '100%': string }> = {
      0: {
        '0%': '#52c41a',
        '100%': '#87d068',
      },
      1: {
        '0%': '#1890ff',
        '100%': '#69c0ff',
      },
      2: {
        '0%': '#722ed1',
        '100%': '#b37feb',
      },
    }
    return colors[level] || colors[0]
  }

  // 格式化文件大小
  const formatSize = (bytes: number) => {
    if (bytes === 0) return '0 B'
    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  // 格式化日期
  const formatDate = (timestamp: number) => {
    return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')
  }

  // 获取空间详情
  const route = useRoute()
  const fetchSpaceDetail = async () => {
    loading.value = true
    try {
      const res = await tuanduikongjianmokuai.getSpaceDetailUsingGet({
        spaceId: Number(route.params.spaceId),
      })
      if (res.data.code === 200) {
        spaceDetail.value = res.data.data
      } else {
        message.error(res.data.message || '获取空间详情失败')
      }
    } catch {
      message.error('获取空间详情失败')
    } finally {
      loading.value = false
    }
  }

  // 存储空间图表配置
  const storageChartOption = computed(() => {
    if (!spaceDetail.value) return {}

    const usedSize = spaceDetail.value.totalSize
    const maxSize = spaceDetail.value.maxSize
    const remainingSize = maxSize - usedSize

    return {
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)',
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        textStyle: {
          color: '#666',
        },
      },
      series: [
        {
          type: 'pie',
          radius: ['60%', '80%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2,
          },
          label: {
            show: false,
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '12',
              fontWeight: 'bold',
            },
          },
          labelLine: {
            show: false,
          },
          data: [
            {
              value: usedSize,
              name: '已使用',
              itemStyle: { color: getSpaceLevelColor(spaceDetail.value.spaceLevel) },
            },
            {
              value: remainingSize,
              name: '剩余空间',
              itemStyle: { color: '#E8EEF2' },
            },
          ],
        },
      ],
    }
  })

  // 成员统计图表配置
  const memberChartOption = computed(() => {
    if (!spaceDetail.value) return {}

    return {
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)',
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        textStyle: {
          color: '#666',
        },
      },
      series: [
        {
          type: 'pie',
          radius: ['60%', '80%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2,
          },
          label: {
            show: false,
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '12',
              fontWeight: 'bold',
            },
          },
          labelLine: {
            show: false,
          },
          data: [
            {
              value: spaceDetail.value.adminCount,
              name: '管理员',
              itemStyle: { color: '#FFB200' },
            },
            {
              value: spaceDetail.value.normalCount,
              name: '普通成员',
              itemStyle: { color: '#36CBCB' },
            },
          ],
        },
      ],
    }
  })

  // 活跃度图表配置 (示例数据)
  const activityChartOption = computed(() => ({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      axisLine: {
        lineStyle: {
          color: '#999',
        },
      },
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#999',
        },
      },
    },
    series: [
      {
        data: [120, 200, 150, 80, 70, 110, 130],
        type: 'line',
        smooth: true,
        lineStyle: {
          color: getSpaceLevelColor(spaceDetail.value?.spaceLevel || 0),
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: getSpaceLevelColor(spaceDetail.value?.spaceLevel || 0),
              },
              {
                offset: 1,
                color: 'rgba(255, 255, 255, 0.1)',
              },
            ],
          },
        },
      },
    ],
  }))

  onMounted(() => {
    fetchSpaceDetail()
  })
</script>

<style scoped>
  .space-detail-container {
    padding: 0 0px;
    background: #fff;
    min-height: calc(100vh - 64px);
  }

  .detail-header {
    background: #fff;
    padding: 12px 0;
    margin-bottom: 16px;
    border-radius: 8px;
    border-bottom: 1px solid #f0f0f0;
  }

  .header-content {
    max-width: 1200px;
    margin: 0 auto;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 16px;
  }

  .header-title {
    display: flex;
    align-items: center;
  }

  .header-title :deep(.ant-tag) {
    margin: 0;
    font-size: 14px;
    padding: 4px 12px;
    border-radius: 4px;
  }

  .header-right {
    display: flex;
    align-items: center;
  }

  .meta-info {
    display: flex;
    gap: 32px;
    color: #666;
    font-size: 13px;
  }

  .meta-item {
    display: flex;
    align-items: center;
    gap: 6px;
  }

  .meta-item :deep(.anticon) {
    font-size: 14px;
    opacity: 0.8;
  }

  .stats-section {
    margin-bottom: 12px;
  }

  .stat-card {
    border-radius: 6px;
    overflow: hidden;
    transition: all 0.3s;
    height: 100%;
  }

  .card-title {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 15px;
    font-weight: 500;
  }

  .chart-container {
    height: 180px;
    margin-bottom: 12px;
  }

  .chart {
    height: 100%;
    width: 100%;
  }

  .stat-content {
    padding: 12px;
  }

  .stat-main {
    text-align: center;
    margin-bottom: 12px;
  }

  .stat-number {
    font-size: 32px;
    font-weight: 600;
    line-height: 1.2;
    margin-bottom: 6px;
  }

  .stat-label {
    font-size: 14px;
    color: #666;
  }

  .member-stats {
    margin-top: 16px;
  }

  .member-stat-item {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;
    color: #666;
  }

  /* 旗舰版特效 */
  .flagship-space {
    position: relative;
    overflow: hidden;
    border: 1px solid #efdbff;
    background: linear-gradient(135deg, #fcf6ff 0%, #f9f0ff 100%);
  }

  .flagship-space::before {
    content: '';
    position: absolute;
    top: -50%;
    left: -50%;
    width: 200%;
    height: 200%;
    background: linear-gradient(
      45deg,
      transparent 0%,
      rgba(255, 255, 255, 0.1) 50%,
      transparent 100%
    );
    animation: shine 3s infinite;
    pointer-events: none;
  }

  .flagship-space .stat-number {
    background: linear-gradient(45deg, #722ed1, #eb2f96);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    animation: pulse 2s infinite;
  }

  .flagship-space .card-title {
    background: linear-gradient(45deg, #722ed1, #eb2f96);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
  }

  /* 专业版特效 */
  .pro-space {
    position: relative;
    overflow: hidden;
    border: 1px solid #bae7ff;
    background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
  }

  .pro-space::before {
    content: '';
    position: absolute;
    top: -50%;
    left: -50%;
    width: 200%;
    height: 200%;
    background: linear-gradient(
      45deg,
      transparent 0%,
      rgba(255, 255, 255, 0.1) 50%,
      transparent 100%
    );
    animation: shine 4s infinite;
    pointer-events: none;
  }

  .pro-space .stat-number {
    background: linear-gradient(45deg, #1890ff, #69c0ff);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
  }

  .pro-space .card-title {
    background: linear-gradient(45deg, #1890ff, #69c0ff);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
  }

  /* 普通版样式 */
  .normal-space {
    border: 1px solid #d9f7be;
    background: linear-gradient(135deg, #f6ffed 0%, #f0f9eb 100%);
  }

  .normal-space .stat-number {
    color: #52c41a;
  }

  .normal-space .card-title {
    color: #52c41a;
  }

  /* 动画效果 */
  @keyframes shine {
    0% {
      transform: translate(-50%, -50%) rotate(0deg);
    }
    100% {
      transform: translate(-50%, -50%) rotate(360deg);
    }
  }

  @keyframes pulse {
    0% {
      transform: scale(1);
    }
    50% {
      transform: scale(1.05);
    }
    100% {
      transform: scale(1);
    }
  }

  /* 卡片悬浮效果 */
  .stat-card {
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  }

  .stat-card:hover {
    transform: translateY(-4px);
  }

  .normal-space.stat-card:hover {
    box-shadow: 0 8px 16px rgba(82, 196, 26, 0.15);
  }

  .pro-space.stat-card:hover {
    box-shadow: 0 8px 16px rgba(24, 144, 255, 0.15);
  }

  .flagship-space.stat-card:hover {
    box-shadow: 0 8px 24px rgba(114, 46, 209, 0.2);
  }

  /* 进度条样式 */
  .flagship-space :deep(.ant-progress-bg) {
    background: linear-gradient(90deg, #722ed1, #eb2f96);
  }

  .pro-space :deep(.ant-progress-bg) {
    background: linear-gradient(90deg, #1890ff, #69c0ff);
  }

  .normal-space :deep(.ant-progress-bg) {
    background: linear-gradient(90deg, #52c41a, #95de64);
  }

  /* 成员列表样式 */
  .members-section {
    margin-top: 16px;
  }

  .members-section .ant-card {
    border-radius: 6px;
  }

  :deep(.ant-table) {
    background: transparent;
  }

  :deep(.ant-table-thead > tr > th) {
    background: transparent;
    font-weight: 500;
  }

  :deep(.ant-table-tbody > tr > td) {
    background: transparent;
  }

  :deep(.ant-table-tbody > tr:hover > td) {
    background: rgba(0, 0, 0, 0.02);
  }
</style>
